package com.lagou.rpc.provider.server;

import com.lagou.rpc.provider.handler.RpcServerHandler;
import com.lagou.rpc.registry.RegistryDiscoveryCenter;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 启动类
 */
@Service
public class RpcServer implements DisposableBean {

    private NioEventLoopGroup bossGroup;

    private NioEventLoopGroup workerGroup;

    @Autowired
    private RpcServerHandler rpcServerHandler;


    public void startServer(String ip, int port) {
        System.out.println("启动服务器:" + ip + ":" + port);
        try {
            //1. 创建线程组
            bossGroup = new NioEventLoopGroup(1);
            workerGroup = new NioEventLoopGroup();
            //2. 创建服务端启动助手
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //3. 设置参数
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            //添加String的编解码器，因为这里服务端和客户端是通过json串来传递数据的
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            //业务处理类
                            pipeline.addLast(rpcServerHandler);
                        }
                    });
            //4.绑定端口
            ChannelFuture sync = serverBootstrap.bind(ip, port).sync();
            System.out.println("==========服务端启动成功==========");
            //5.将rpc-provider的ip、端口信息注册到zk
            System.out.println("开始向zk注册服务");
            register2Zk(ip, port);
            System.out.println("向zk注册成功");
            sync.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeGroups();
        }
    }

    private void register2Zk(String ip, int port) throws Exception {
        RetryPolicy retryPolicy = new RetryNTimes(1, 1000);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("localhost:2181")
                .sessionTimeoutMs(5000)
                .connectionTimeoutMs(5000)
                .retryPolicy(retryPolicy)
                .build();
        String serverInfo = ip + ":" + port;
        client.getConnectionStateListenable().addListener((CuratorFramework curatorFramework, ConnectionState connectionState) -> {
            if (ConnectionState.CONNECTED.equals(connectionState)) {
                System.out.println(String.format("provider[%s]连接至zk服务器成功", serverInfo));
            }
        });
        // 启动
        client.start();

        // 1.先创建根节点（如果不存在的话），/rpc-providers，该节点是持久节点，后续要该节点下的每一个子节点对应一个rpc-provider
        String rootNodePath = RegistryDiscoveryCenter.ZK_RPC_SERVERS_ROOT_PATH;
        if (client.checkExists().forPath(rootNodePath) == null) {
            client.create().withMode(CreateMode.PERSISTENT).forPath(rootNodePath);
        }
        // 2.在根节点下创建临时节点
        // 每一个节点的名称就是provider的ip和端口信息，格式形如ip:port，客户端要根据这里的ip和端口来向provider发送rpc请求
        String path = RegistryDiscoveryCenter.ZK_RPC_SERVERS_ROOT_PATH + "/" + serverInfo;
        path = client.create().withMode(CreateMode.EPHEMERAL).forPath(path);
        System.out.println(String.format("节点[%s]创建成功", path));
    }


    @Override
    public void destroy() throws Exception {
        closeGroups();
    }

    private void closeGroups() {
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }

        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
    }
}
